package com.yoyo.framework.shiro.service;

import com.yoyo.common.utils.StringUtils;
import com.yoyo.framework.shiro.session.OnlineSession;
import com.yoyo.system.domain.SysUserOnline;
import com.yoyo.system.service.ISysUserOnlineService;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.Serializable;

/**
 * @author zyl
 * @Date 2021/7/3 -15:38
 */
@Component
public class SysShiroService {
    @Autowired
    private ISysUserOnlineService onlineService;

    /**
     * 获取会话信息
     *
     * @param sessionId
     * @return
     */
    public Session getSession(Serializable sessionId) {
        SysUserOnline sysUserOnline = onlineService.selectOnlineById(String.valueOf(sessionId));
        return StringUtils.isNull(sysUserOnline) ? null : createSession(sysUserOnline);
    }

    private Session createSession(SysUserOnline sysUserOnline) {
        OnlineSession onlineSession = new OnlineSession();
        if (StringUtils.isNotNull(onlineSession)) {
            onlineSession.setId(sysUserOnline.getSessionId());
            onlineSession.setHost(sysUserOnline.getIpaddr());
            onlineSession.setBrowser(sysUserOnline.getBrowser());
            onlineSession.setOs(sysUserOnline.getOs());
            onlineSession.setDeptName(sysUserOnline.getDeptName());
            onlineSession.setLoginName(sysUserOnline.getLoginName());
            onlineSession.setStartTimestamp(sysUserOnline.getStartTimestamp());
            onlineSession.setLastAccessTime(sysUserOnline.getLastAccessTime());
            onlineSession.setTimeout(sysUserOnline.getExpireTime());
        }
        return onlineSession;
    }

    public void deleteSession(OnlineSession onlineSession) {
        onlineService.deleteOnlineById(String.valueOf(onlineSession.getId()));
    }
}
